package org.ubc.cs410.disposal2020.testcase;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;

import org.ubc.cs410.disposal2020.BuildingBoundary;
import org.ubc.cs410.disposal2020.Map;
import org.ubc.cs410.disposal2020.PMF;
import org.ubc.cs410.disposal2020.server.MapServiceImpl;

import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Query;

public class MapDatastoreTestCase extends LocalDatastoreTestCase {

	public void testInsert() {
		Query query = new Query(Map.class.getSimpleName());
		int mapCount = DatastoreServiceFactory.getDatastoreService().prepare(
				query).countEntities();
		Map map = createMapStubs();
		map = MapServiceImpl.insertMap2Datastore(map);

		assertEquals(mapCount + 1, DatastoreServiceFactory
				.getDatastoreService().prepare(query).countEntities());

	}

	public void testDelete() {
		Query query = new Query(Map.class.getSimpleName());
		int mapCount = DatastoreServiceFactory.getDatastoreService().prepare(
				query).countEntities();
		Map map = createMapStubs();
		map = MapServiceImpl.insertMap2Datastore(map);

		assertEquals(mapCount + 1, DatastoreServiceFactory
				.getDatastoreService().prepare(query).countEntities());

		map = getMap(map.getName());
		deleteMap(map);

		assertEquals(mapCount, DatastoreServiceFactory
				.getDatastoreService().prepare(query).countEntities());
	}

	private static Set<BuildingBoundary> createBuildingBoundaryStubs() {
		return new HashSet<BuildingBoundary>();
	}

	private static Map createMapStubs() {
		Date date = new Date();
		String name = "testing-";
		name += date.toString();
		Map map = new Map(name, date.toString(), Integer.valueOf(0), Float
				.valueOf(0), Float.valueOf(0), Integer.valueOf(0),
				createBuildingBoundaryStubs());
		return map;
	}

	protected static Map getMap(String mapName) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
        Map map = null;

        javax.jdo.Query q = pm.newQuery(Map.class, "name == '" + mapName + "'");
        List<Map> results = (List<Map>) q.execute();

        if (results.size() == 1) {
                map = results.get(0);
        }

        return map;
	}


	protected static void deleteMap(Map map) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.deletePersistent(map);
		} finally {
			pm.close();
		}
	}
}
